import request from './request'

// 商品分类详细信息
export interface Category {
  id: number
  name: string
  description?: string
  image?: string
  icon?: string
  parentId?: number
  level: number
  sort: number
  status: 'active' | 'inactive'
  productCount?: number
  children?: Category[]
  parent?: Category
  createdAt: string
  updatedAt: string
}

// 分类树节点
export interface CategoryTree {
  id: number
  name: string
  image?: string
  icon?: string
  children?: CategoryTree[]
  productCount?: number
}

// 分类查询参数
export interface CategoryQuery {
  parentId?: number
  level?: number
  status?: 'active' | 'inactive'
  includeChildren?: boolean
  includeProductCount?: boolean
}

// 热门分类
export interface HotCategory {
  id: number
  name: string
  image: string
  productCount: number
  hotProducts?: Array<{
    id: number
    name: string
    image: string
    price: number
  }>
}

export const categoryApi = {
  // 获取所有分类（树形结构）
  getCategoryTree: (params?: { includeProductCount?: boolean }) => {
    return request.get<CategoryTree[]>('/api/categories/tree', { params })
  },

  // 获取分类列表（平铺结构）
  getCategories: (params?: CategoryQuery) => {
    return request.get<Category[]>('/api/categories', { params })
  },

  // 获取顶级分类
  getTopCategories: (params?: { includeProductCount?: boolean }) => {
    return request.get<Category[]>('/api/categories/top', { params })
  },

  // 获取子分类
  getChildCategories: (parentId: number, params?: { includeProductCount?: boolean }) => {
    return request.get<Category[]>(`/api/categories/${parentId}/children`, { params })
  },

  // 获取分类详情
  getCategoryById: (id: number, params?: { includeChildren?: boolean; includeProductCount?: boolean }) => {
    return request.get<Category>(`/api/categories/${id}`, { params })
  },

  // 获取分类路径（面包屑）
  getCategoryPath: (id: number) => {
    return request.get<Category[]>(`/api/categories/${id}/path`)
  },

  // 获取热门分类
  getHotCategories: (limit = 8) => {
    return request.get<HotCategory[]>('/api/categories/hot', { params: { limit } })
  },

  // 获取推荐分类
  getRecommendedCategories: (limit = 6) => {
    return request.get<Category[]>('/api/categories/recommended', { params: { limit } })
  },

  // 根据分类获取商品
  getProductsByCategory: (categoryId: number, params?: {
    page?: number
    limit?: number
    sortBy?: 'price' | 'sales' | 'createdAt'
    sortOrder?: 'asc' | 'desc'
    minPrice?: number
    maxPrice?: number
  }) => {
    return request.get(`/api/categories/${categoryId}/products`, { params })
  },

  // 搜索分类
  searchCategories: (keyword: string, params?: { limit?: number }) => {
    return request.get<Category[]>('/api/categories/search', { params: { keyword, ...params } })
  }
}
